import { LOGIN_TOKEN } from '@/global/constant'
import { localCache } from '@/utils/cache'
import { defaultUrl } from '@/utils/map-menus'
import { createRouter, createWebHashHistory, type RouteRecordRaw } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/main' // 默认跳转到 main，需要做导航守卫，如果没有登录的话就再跳转到login
    },
    {
      path: '/login',
      component: () => import('@/views/login/login-page.vue')
    },
    {
      path: '/main',
      name: 'main',
      component: () => import('@/views/main/main-page.vue'),
      children: []
    },
    {
      path: '/:pathMatch(.*)*',
      component: () => import('@/views/not-found/not-found.vue')
    }
  ]
})

// 路由守卫：输入域名后，有登录信息token就直接遵循重定向进入main页面，否则跳转到login页面
/**
 * beforeEach：在路由跳转之前执行，
 *  其回调函数参数2个：to/from，to表示要跳转到哪个页面，from表示从哪个页面跳转过来的
 *  其回调函数返回值: 表示导航到哪个页面
 */
router.beforeEach((to) => {
  const token = localCache.getCache(LOGIN_TOKEN)
  if (to.path.startsWith('/main') && !token) {
    // 返回值表示导航到哪个页面
    return '/login'
  }
  if (to.path === '/main') {
    return defaultUrl.url
  }
})

// 1. 用于动态添加路由的路由映射
export const routeListMap: RouteRecordRaw[] = [
  {
    path: '/main/analysis/overview',
    component: () => import('@/views/main/analysis/overview/overview-page.vue')
  },
  {
    path: '/main/analysis/dashboard',
    component: () => import('@/views/main/analysis/dashboard/dashboard-page.vue')
  },
  {
    path: '/main/system/user',
    component: () => import('@/views/main/system/user/user-manage.vue')
  }
]
// 2.动态添加路由 (在 src\store\login\login.ts 实现)
// router.addRoute('main', routeListMap[0])

export default router
